package com.hooper.iot.resource.impl;

import com.hooper.iot.cache.UnifyDeviceCache;
import com.hooper.iot.resource.entity.UnifyDevNotifyMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Objects;

/**
 * @Author :     WANGCHENG
 * @Date :     2022/6/6 13:34
 * @Version:
 * @Description
 */
@Service
@Slf4j
public class UnifyDevServiceImpl {

    @Autowired
    private UnifyDeviceCache unifyDeviceCache;

    public void handleMessage(UnifyDevNotifyMessage message) {
        if (Objects.isNull(message) || Objects.isNull(message.getDeviceMsgs())) {
            log.error("消息参数不全，忽略");
            return;
        }
        message.getDeviceMsgs().forEach(deviceMsg -> {
            // 忽略无设备类型的消息
            if (!ObjectUtils.isEmpty(deviceMsg.getDeviceType())) {
                uptDeviceCache(deviceMsg.getId(), deviceMsg.getOperateType());
            }
        });
    }

    // 更新设备缓存
    private void uptDeviceCache(String devId, int operateType) {
        if (operateType == 3) {
            unifyDeviceCache.findDevice(devId);
        } else if (operateType == 4) {
            unifyDeviceCache.uptDevice(devId);
        } else if (operateType == 5) {
            unifyDeviceCache.delDevice(devId);
        }
    }
}
